package com.zHan.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zHan.sky.common.contant.MessageConstant;
import com.zHan.sky.common.content.BaseContext;
import com.zHan.sky.common.exception.AddressBookBusinessException;
import com.zHan.sky.common.exception.OrderBusinessException;
import com.zHan.sky.common.exception.ShoppingCartBusinessException;
import com.zHan.sky.common.utils.WeChatPayUtil;
import com.zHan.sky.controller.nofity.PayNotifyController;
import com.zHan.sky.dto.*;
import com.zHan.sky.entity.AddressBook;
import com.zHan.sky.entity.OrderDetail;
import com.zHan.sky.entity.Orders;
import com.zHan.sky.entity.ShoppingCart;
import com.zHan.sky.mapper.OrdersMapper;
import com.zHan.sky.service.*;
import com.zHan.sky.vo.OrderPaymentVO;
import com.zHan.sky.vo.OrderStatisticsVO;
import com.zHan.sky.vo.OrderSubmitVO;
import com.zHan.sky.vo.OrderVO;
import com.zHan.sky.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private UserService userService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Autowired
    private PayNotifyController payNotifyController;

    @Autowired
    private WebSocketServer webSocketServer;


    /**
     * 提交订单
     *
     * @param ordersSubmitDTO
     */
    @Override
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        // 处理各类业务异常
        // 查询地址簿数据
        Long addressBookId = ordersSubmitDTO.getAddressBookId();
        AddressBook addressBook = addressBookService.getById(addressBookId);
        // 地址簿数据为空
        if (ObjectUtils.isEmpty(addressBook)) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        // 根据用户id查询购物车数据
        Long userId = BaseContext.getCurrentId();
        List<ShoppingCart> shoppingCartList =
                shoppingCartService.lambdaQuery().eq(ShoppingCart::getUserId,
                        userId).list();
        // 购物车数据为空
        if (ObjectUtils.isEmpty(shoppingCartList)) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        // 向订单表插入一条数据
        // 构造对象
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setAddress(addressBook.getDetail());
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setUserId(userId);
        // 插入数据
        save(orders);

        // 向订单明细表插入多条数据
        // 创建orderDetail集合对象并拷贝
        List<OrderDetail> orderDetailList = new ArrayList<>();
        shoppingCartList.stream().forEach((shoppingCart -> {
            OrderDetail orderDetail = new OrderDetail();//订单明细
            BeanUtils.copyProperties(shoppingCart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }));

        // 插入数据
        orderDetailService.saveBatch(orderDetailList);

        // 清空用户的购物车数据
        shoppingCartService.clean();
        // 封装VO返回
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();

        return orderSubmitVO;

    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO,
                                  HttpServletResponse response) throws Exception {
/*        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userService.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals(
                "ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO orderPaymentVO = jsonObject.toJavaObject(OrderPaymentVO.class);
        orderPaymentVO.setPackageStr(jsonObject.getString("package"));*/

        // 由于没有支付的一些证书，所有直接支付成功。
        OrderPaymentVO orderPaymentVO = new OrderPaymentVO();
        paySuccess(ordersPaymentDTO.getOrderNumber());

        // 给微信响应
        payNotifyController.responseToWeixin(response);

        return orderPaymentVO;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = lambdaQuery()
                .eq(Orders::getNumber, outTradeNo)
                .eq(Orders::getUserId, userId)
                .one();

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();
        // 执行修改方法
        updateById(orders);

        // 通过webSocket向客户端浏览器传递消息
        // 封装map集合
        Map map = new HashMap();
        map.put("type", 1);  // 1表示来单提醒
        map.put("orderId", ordersDB.getId());
        map.put("content", "订单号" + outTradeNo);
        // 转换成字符串
        String json = JSON.toJSONString(map);
        // 发送消息
        webSocketServer.sendToAllClient(json);
    }

    /**
     * 再来一单
     *
     * @param id
     */
    @Override
    public void repetition(Long id) {
        //清空购物车
        shoppingCartService.clean();
        //条件构造器
        LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<>();
        //过滤条件
        queryWrapper.eq(OrderDetail::getOrderId, id);
        //执行方法
        List<OrderDetail> orderDetailList = orderDetailService.list(queryWrapper);
        List<ShoppingCart> shoppingCartList = new ArrayList<>();

        orderDetailList.forEach((item) -> {
            //创建一个购物车对象
            ShoppingCart shoppingCart = new ShoppingCart();

            Long dishId = item.getDishId();
            Long setmealId = item.getSetmealId();

            //给购物车对象赋值
            if (dishId != null) {
                shoppingCart.setDishId(dishId);
                shoppingCart.setDishFlavor(item.getDishFlavor());
            } else {
                shoppingCart.setSetmealId(setmealId);
            }
            shoppingCart.setName(item.getName());
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCart.setAmount(item.getAmount());
            shoppingCart.setImage(item.getImage());
            shoppingCart.setNumber(item.getNumber());

            shoppingCartList.add(shoppingCart);
        });

        //批量加入到购物车中
        shoppingCartService.saveBatch(shoppingCartList);
    }

    /**
     * 历史订单查询
     *
     * @param page
     * @param pageSize
     * @param status
     * @return
     */
    @Override
    public Page<OrderVO> historyOrders(int page, int pageSize, Integer status) {
        //分页构造器
        Page<Orders> pageInfo = new Page<>(page, pageSize);
        Page<OrderVO> orderVOPage = new Page<>();
        //条件构造器
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getUserId, BaseContext.getCurrentId())
                .eq(status != null, Orders::getStatus, status)
                .orderByDesc(Orders::getOrderTime);
        //执行方法
        this.page(pageInfo, queryWrapper);

        //对象拷贝
        BeanUtils.copyProperties(pageInfo, orderVOPage, "records");
        List<Orders> records = pageInfo.getRecords();

        List<OrderVO> orderVOList = new ArrayList<>();

        records.forEach((item) -> {
            //创建ordersDto对象
            OrderVO orderVO = new OrderVO();

            //对象拷贝
            BeanUtils.copyProperties(item, orderVO);

            //获得订单id
            Long orderId = item.getId();

            LambdaQueryWrapper<OrderDetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(OrderDetail::getOrderId, orderId);

            //查询订单详细
            List<OrderDetail> orderDetailList = orderDetailService.list(lambdaQueryWrapper);

            orderVO.setOrderDetailList(orderDetailList);
            orderVOList.add(orderVO);
        });

        orderVOPage.setRecords(orderVOList);
        return orderVOPage;
    }

    /**
     * 取消订单
     *
     * @param ordersCancelDTO
     */
    @Override
    public void cancelOrder(OrdersCancelDTO ordersCancelDTO) {
        String cancelReason = ordersCancelDTO.getCancelReason();
        // 查询订单
        Orders ordersDB = lambdaQuery().eq(Orders::getId, ordersCancelDTO.getId()).one();

        // 订单为空
        if (ordersDB == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        // 判断是否已支付订单
        if (Orders.PAID.equals(ordersDB.getPayStatus())) {
            // 模拟 执行退款流程
            System.out.println("已退款");
        }

        // 赋值并修改订单状态
        Orders orders = Orders.builder()
                .id(ordersCancelDTO.getId())
                .cancelReason(cancelReason)
                .status(Orders.CANCELLED)
                .cancelTime(LocalDateTime.now())
                .build();
        // 执行修改方法
        updateById(orders);
    }

    /**
     * 拒单
     *
     * @param ordersRejectionDTO
     */
    @Override
    public void rejectionOrder(OrdersRejectionDTO ordersRejectionDTO) {
        String rejectionReason = ordersRejectionDTO.getRejectionReason();
        // 查询订单
        Orders ordersDB = lambdaQuery().eq(Orders::getId, ordersRejectionDTO.getId()).one();
        // 订单只有存在且状态为待接单才可以拒单
        if (ordersDB == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        if (!Orders.TO_BE_CONFIRMED.equals(ordersDB.getStatus())) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        // 如果已经付了款
        if (Orders.PAID.equals(ordersDB.getPayStatus())) {
            // 模拟执行退款流程
            System.out.println("已退款");
        }

        Orders orders = Orders.builder()
                .id(ordersRejectionDTO.getId())
                .rejectionReason(rejectionReason)
                .status(Orders.CANCELLED)
                .build();
        // 执行修改方法
        updateById(orders);
    }

    /**
     * 接单
     *
     * @param ordersConfirmDTO
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = lambdaQuery()
                .eq(Orders::getId, ordersConfirmDTO.getId())
                .one();
        // 校验订单是否存在，并且状态为待接单
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        if (!orders.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        orders.setStatus(Orders.CONFIRMED);
        updateById(orders);
    }

    /**
     * 完成订单
     *
     * @param id
     */
    @Override
    public void complete(Long id) {
        Orders orders = lambdaQuery().eq(Orders::getId, id).one();
        // 校验订单是否存在，并且状态为已派送
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        if (!orders.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 状态修改为已完成
        orders.setStatus(Orders.COMPLETED);
        // 设置送达时间
        orders.setDeliveryTime(LocalDateTime.now());
        updateById(orders);
    }

    /**
     * 派送订单
     *
     * @param id
     */
    @Override
    public void delivery(Long id) {
        Orders orders = lambdaQuery().eq(Orders::getId, id).one();
        // 校验订单是否存在，并且状态为已接单
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        if (!orders.getStatus().equals(Orders.CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 状态修改为派送中
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        updateById(orders);
    }

    /**
     * 订单搜索
     *
     * @param page
     * @param pageSize
     * @param number
     * @param beginTime
     * @param endTime
     * @param phone
     * @return
     */
    @Override
    public Page<Orders> conditionSearch(int page, int pageSize, Long number, String beginTime,
                                        String endTime, String phone, Integer status) {
        //分页构造器
        Page<Orders> pageInfo = new Page<>(page, pageSize);

        //条件查询构造器
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        //过滤条件
        queryWrapper.like(number != null, Orders::getNumber, number)
                .like(phone != null, Orders::getPhone, phone)
                .eq(status != null, Orders::getStatus, status)
                .between(org.apache.commons.lang.StringUtils.isNotEmpty(beginTime) && org.apache.commons.lang.StringUtils.isNotEmpty(endTime),
                        Orders::getOrderTime, beginTime, endTime)
                .orderByDesc(Orders::getOrderTime);

        //执行方法
        page(pageInfo, queryWrapper);
        return pageInfo;
    }

    /**
     * 查询订单详情
     *
     * @param id
     * @return
     */
    @Override
    public OrderVO details(Long id) {
        // 查询订单
        Orders orders = lambdaQuery().eq(Orders::getId, id).one();
        // 查询订单详情
        List<OrderDetail> orderDetailList =
                orderDetailService.lambdaQuery().eq(OrderDetail::getOrderId, orders.getId()).list();
        // 创建对象
        OrderVO orderVO = new OrderVO();
        // 对象拷贝
        BeanUtils.copyProperties(orders, orderVO);
        // 对象赋值
        orderVO.setOrderDetailList(orderDetailList);
        return orderVO;
    }

    /**
     * 用户取消订单
     *
     * @param id
     */
    @Override
    public void userCancelOrderById(Long id) {
        // 查询订单
        Orders orders = lambdaQuery().eq(Orders::getId, id).one();
        // 未查询到订单
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        // 如果已派送，不能退款
        if (orders.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 订单处于待接单状态下取消，需要进行退款
        if (orders.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            // 模拟退款流程
            System.out.println("已退款");
            //支付状态修改为 退款
            orders.setPayStatus(Orders.REFUND);
        }

        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());
        // 执行方法
        updateById(orders);
    }

    /**
     * 各个状态的订单数量统计
     *
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        // 查询统计数量
        // 待接单
        Integer toBeConfirmed = getStatusCount(null, null, Orders.TO_BE_CONFIRMED);
        // 已接单
        Integer confirmed = getStatusCount(null, null, Orders.CONFIRMED);
        // 派送中
        Integer deliveryInProgress =
                getStatusCount(null, null,  Orders.DELIVERY_IN_PROGRESS);

        // 封装对象并返回
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderStatisticsVO;
    }

    /**
     * 获得各个状态的订单数
     * @param beginTime
     * @param endTime
     * @param status
     * @return
     */
    @Override
    public Integer getStatusCount(LocalDateTime beginTime, LocalDateTime endTime, Integer status) {
        return lambdaQuery()
                .gt(beginTime != null, Orders::getOrderTime, beginTime)
                .lt(endTime != null, Orders::getOrderTime, endTime)
                .eq(status!=null,Orders::getStatus, status).count();
    }

    /**
     * 客户催单
     *
     * @param id
     */
    @Override
    public void reminder(Long id) {
        // 查询订单
        Orders orders = lambdaQuery().eq(Orders::getId, id).one();
        // 判断订单是否存在
        // 未查询到订单
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        // 通过webSocket向客户端浏览器传递消息
        // 封装map集合
        Map map = new HashMap();
        map.put("type", 2);  // 2表示客户催单
        map.put("orderId", id);
        map.put("content", "订单号：" + orders.getNumber());
        // 转换成字符串
        String json = JSON.toJSONString(map);
        // 发送消息
        webSocketServer.sendToAllClient(json);
    }

    /**
     * 查询有效订单数
     *
     * @param beginTime
     * @param endTime
     * @return
     */
    @Override
    public Integer getOrderCount(LocalDateTime beginTime, LocalDateTime endTime,
                                 Integer status) {
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.gt(beginTime != null, Orders::getOrderTime, beginTime)
                .lt(endTime != null, Orders::getOrderTime, endTime)
                .eq(status != null, Orders::getStatus, status);
        return baseMapper.selectCount(queryWrapper);
    }


}
